package cc.admin.modules.graduate.controller;

import cc.admin.common.api.vo.Result;
import cc.admin.common.aspect.annotation.AutoLog;
import cc.admin.common.sys.base.controller.BaseController;
import cc.admin.common.sys.query.QueryGenerator;
import cc.admin.modules.graduate.entity.BlankErrorQuestions;
import cc.admin.modules.graduate.entity.BlankQuestions;
import cc.admin.modules.graduate.entity.Category;
import cc.admin.modules.graduate.entity.ChoiceQuestions;
import cc.admin.modules.graduate.service.IBlankErrorQuestionsService;
import cc.admin.modules.graduate.service.IBlankQuestionsService;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Api(tags = "填空题")
@RestController
@RequestMapping("/blank/blankQuestions")
@Slf4j
public class BlankQuestionsController extends BaseController<BlankQuestions, IBlankQuestionsService> {
    @Autowired
    private IBlankQuestionsService blankQuestionsService;

    @Autowired
    private IBlankErrorQuestionsService blankErrorQuestionsService;

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "填空题-分页列表查询")
    @ApiOperation(value = "填空题-分页列表查询", notes = "填空题-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(@RequestParam(name="key",required = false) String key,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<BlankQuestions> queryWrapper = QueryGenerator.initQueryWrapper(new BlankQuestions(), req.getParameterMap());
        if (StrUtil.isNotEmpty(key)) {
            queryWrapper.like("question",key);
        }
        Map<String, String[]> parameterMap = req.getParameterMap();
        String[] catalogs = parameterMap.get("catalog");
        String tab = catalogs[0];
        queryWrapper.eq("major_id",tab);

        Page<BlankQuestions> page = new Page<BlankQuestions>(pageNo, pageSize);
        IPage<BlankQuestions> pageList = blankQuestionsService.page(page, queryWrapper);

        List<BlankQuestions> records = pageList.getRecords();

        // 遍历每个选择题
        records.forEach(blankQuestions1 -> {
            // 定义每个选择题里面的下拉框
            ArrayList<Category> categories = new ArrayList<>();
            //当存在下拉数据时
            if (blankQuestions1.getCategoryIds()!=null&&blankQuestions1.getCategoryIdsText()!=null){
                String[] split = blankQuestions1.getCategoryIds().split(",");
                String[] split2 = blankQuestions1.getCategoryIdsText().split(",");
                for (int i = 0; i < split.length; i++) {
                    Category category = new Category(split[i],split2[i]);
                    categories.add(category);
                }
            }
            blankQuestions1.setCategorys(categories);
        });
        pageList.setRecords(records);





        return Result.ok(pageList);
    }



    public BlankQuestions setCategory(BlankQuestions blankQuestions) {
        List<Category> categorys = blankQuestions.getCategorys();
        ArrayList<String> categoryIds = new ArrayList<>();
        ArrayList<String> categoryIdsText = new ArrayList<>();
        if (categorys!=null&&categorys.size()>0) {
            categorys.forEach(category -> {
                categoryIds.add(category.getValue());
                categoryIdsText.add(category.getLabel());
            });
            blankQuestions.setCategoryIds(String.join(",",categoryIds));
            blankQuestions.setCategoryIdsText(String.join(",",categoryIdsText));
        }

        return blankQuestions;
    }


    /**
     * 添加
     *
     * @param blankQuestions
     * @return
     */
    @AutoLog(value = "填空题-添加")
    @ApiOperation(value = "填空题-添加", notes = "填空题-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody BlankQuestions blankQuestions) {
        blankQuestions = setCategory(blankQuestions);
        blankQuestionsService.save(blankQuestions);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param blankQuestions
     * @return
     */
    @AutoLog(value = "填空题-编辑")
    @ApiOperation(value = "填空题-编辑", notes = "填空题-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody BlankQuestions blankQuestions) {
        blankQuestions = setCategory(blankQuestions);
        //讲解视频路径
        String viedoUrl2 = blankQuestions.getViedoUrl2();
        if (viedoUrl2!=null&&!viedoUrl2.equals("")){
            LambdaUpdateWrapper<BlankErrorQuestions> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(BlankErrorQuestions::getQuestionId,blankQuestions.getId());
            updateWrapper.set(BlankErrorQuestions::getViedoUrl2,viedoUrl2);
            blankErrorQuestionsService.update(updateWrapper);
            log.info("修改填空讲解视频完成:{}",blankQuestions);
        }
        blankQuestionsService.updateById(blankQuestions);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "填空题-通过id删除")
    @ApiOperation(value = "填空题-通过id删除", notes = "填空题-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        blankQuestionsService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "填空题-批量删除")
    @ApiOperation(value = "填空题-批量删除", notes = "填空题-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.blankQuestionsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "填空题-通过id查询")
    @ApiOperation(value = "填空题-通过id查询", notes = "填空题-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        BlankQuestions blankQuestions = blankQuestionsService.getById(id);
        if (blankQuestions == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(blankQuestions);
    }


    /**
     * 复制
     *
     * @param id
     * @param name
     * @return
     */
    @AutoLog(value = "填空题-复制")
    @ApiOperation(value = "填空题-复制", notes = "填空题-复制")
    @PostMapping(value = "/copy")
    public Result<?> copy(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "name", required = true) String name) {
        BlankQuestions blankQuestions = blankQuestionsService.getById(id);
        blankQuestions.setId(IdUtil.fastUUID());
        blankQuestions.setCreateTime(new Date());
        blankQuestionsService.save(blankQuestions);
        return Result.ok("复制成功！");
    }


    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(@RequestParam(name="blankQuestions",required = false) String blankQuestionIds, @RequestParam(name="key",required = false) String key, @RequestParam(name="catalog",required = false) String catalog, HttpServletRequest request) {
        return blankQuestionsService.exportXls(request, blankQuestionIds,catalog, BlankQuestions.class, "填空题");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return blankQuestionsService.importExcel(request, response, BlankQuestions.class);
    }


}
